package cz.cuni.mff.ufal.httpserver;

import java.io.IOException;
import java.net.Socket;
import java.util.UUID;

import org.apache.log4j.Logger;

import cz.cuni.mff.ufal.httpserver.protocol.HttpRequest;
import cz.cuni.mff.ufal.httpserver.protocol.HttpResponse;

class HttpServerRequestHandler implements Runnable {

  private final static Logger log = Logger.getLogger(HttpServerRequestHandler.class);

  public HttpServerRequestHandler(Socket socket, HttpRequestHandler handler) {
    this.socket = socket;
    this.handler = handler;
  }

  private final Socket socket;
  private final HttpRequestHandler handler;

  @Override
  public void run() {
  	UUID id = UUID.randomUUID();
  	log.trace("Starting to process the request " + id);
    try {
      HttpRequest request = new HttpRequest(socket.getInputStream());
      HttpResponse response = new HttpResponse(socket.getOutputStream());
      handler.process(request, response);
      response.close();
      log.trace(String.format("The request %s was successfully processed", id.toString()));
    } catch (IOException e) {
      log.error("an I/O exception occurred", e);
    } catch (Throwable cause) {
      log.error("an exception occurred", cause);
    } finally {
      try {
        socket.close();
      } catch (IOException e) {
        log.error("the socket could not be closed, an I/O exception occurred", e);
      }
    }
  }
}

